/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import static controller.BusControl.getApplications;
import docs.InternshipCompanyModel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.validation.Valid;
import model.Utilisateur;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.* ;
import javax.servlet.http.HttpSession;
import model.Applications;
import model.Student;
import org.netbeans.xml.schema.elements.APPLICATION;
import org.netbeans.xml.schema.elements.APPLICATIONTYPE;
import org.netbeans.xml.schema.elements.COMPANYTYPE;
import org.netbeans.xml.schema.elements.LISTIDTYPE;
import org.netbeans.xml.schema.elements.NOTIFSTYPE;
import org.netbeans.xml.schema.elements.PERSONNELTYPE;
import org.netbeans.xml.schema.elements.STUDENTTYPE;
import org.netbeans.xml.schema.elements.USERTYPE;

/**
 *  MAnagement of the connections
 * @author metbill
 */
@Controller
public class ConnectionController {
    
    /**
     * Connection page
     * @return 
     */
    @RequestMapping(value = "/")
    public String welcome() {
        
        return "connection";
        
    }
    
    /**
     * Manage the user connection
     * @param user
     * @param model
     * @param session
     * @return 
     */
    @RequestMapping(value = "/connect", method = RequestMethod.POST)
    public String connect ( @ModelAttribute("SpringWeb")Utilisateur user , ModelMap model ,HttpSession session) {
               
        //appel du service avec login mdp
        int idUser =  BusControl.authenticate(user.getUsername(),user.getPassword());
        if ( idUser != 0) {     
            
                USERTYPE userInfo = BusControl.getinfoUserbyId(idUser);
                int tip = BusControl.getinfoUserbyId(idUser).getTYPE();
                model.addAttribute("type", tip );
                
                // Gestion de la connection de l'étudiant
                 if (tip == 1) {
                   STUDENTTYPE stud = BusControl.getStudentbyId(idUser);
                   // Màj des notifications + création d'object notifs pour les notifs?
                    NOTIFSTYPE test = BusControl.getNotifications(idUser);
                    int notifs = test.getNOTIFS().size();
                    
                    APPLICATIONTYPE listCand = getApplications(idUser);
                    ArrayList<Applications> listCan= new ArrayList<>();
                    
                    if (listCand != null){
                    Iterator<APPLICATION> ite = listCand.getAPPLICATIONS().iterator();
                    
                     while (ite.hasNext()){
                         APPLICATION offer = ite.next();
                         
                         
                         InternshipCompanyModel internships = BusControl.getOffersById(BusControl.getAppById(offer.getApplicationID()).getInternshipID());
                         
                         int appId = offer.getApplicationID();
                         int status = BusControl.getAppById(appId).getStatus();
                         COMPANYTYPE com = BusControl.getCompanybyId(offer.getCompanyID());
                         Applications can = new Applications(appId,null,internships, com.getNOM(), com.getMAIL(), com.getADDRESS(), Utils.getStatus(status));
                         can.setStatusId(status);
                         //int stat = BusControl.getAppById(can.getApplicationId()).getStatus();
                         //On n'affiche pas les stages refuse par l'etudiant
                         if (status != 4){              
                            listCan.add(can);           
                         }
                         
                          //offer.setDescription(offer.getDescription().substring(0,250));
                     }
                    } else {
                        listCan = null;
                    }

                    model.addAttribute("listCan", listCan);
                    
                    Utils.drawHomePage(stud.getFIRSTNAME().toString(), notifs, "searchStudent", "candidatureStudent", model);
                    
                    
                }else if (tip == 3 ){
                  // Traitement connection company 
                    COMPANYTYPE comp = BusControl.getCompanybyId(idUser);
                    NOTIFSTYPE test = BusControl.getNotifications(idUser);
                    List<InternshipCompanyModel> offers = BusControl.getOffers(null);
                    
                    int notifs = test.getNOTIFS().size();
                    Utils.drawHomePageCompany(comp.getNOM(), notifs,  "blank","internshipsCompany",  model, offers);            
                }else if (tip == 2) {
                     
                    PERSONNELTYPE superv = BusControl.getPersonnelbyId(idUser);
                    NOTIFSTYPE test = BusControl.getNotifications(idUser);
                    int notifs = test.getNOTIFS().size();
                    // Traitement Superviseur
                    if (superv.isISADMIN()) {
                        LISTIDTYPE students = BusControl.getStudentsSupervisor(idUser);
                        List<Integer> studentsIds = students.getID();
                        ArrayList<Applications> listCan= new ArrayList<>();
                        
                        for (Integer studId : studentsIds) {
                            STUDENTTYPE stud = BusControl.getStudentbyId(studId);
                            Student student = new Student(studId,(String)stud.getFIRSTNAME(), (String)stud.getLASTNAME(), (String)stud.getMAIL(), (String)stud.getPHONENUMBER(), Integer.valueOf((String)stud.getSUPERVISORID()));
                            
                            APPLICATIONTYPE listCand = getApplications(studId);
                            if (listCand != null){
                                Iterator<APPLICATION> ite = listCand.getAPPLICATIONS().iterator();
                                
                                while (ite.hasNext()){
                                    APPLICATION offer = ite.next();
                                    
                                    
                                    int appId = offer.getApplicationID();
                                    int status = BusControl.getAppById(appId).getStatus();
                                    
                                    InternshipCompanyModel inte = BusControl.getOffersById(BusControl.getAppById(appId).getInternshipID());
                                    
                                    COMPANYTYPE com = BusControl.getCompanybyId(offer.getCompanyID());
                                    Applications can = new Applications(appId,student,inte, com.getNOM(), com.getMAIL(), com.getADDRESS(), Utils.getStatus(status));
                                    
                                    //If status est entre [8,11), on ajoute dans la liste des candidatures
                                    //int stat = BusControl.getAppById(can.getApplicationId()).getStatus();
                                    if (status >= 8 && status <11){
                                        listCan.add(can);
                                    }
                                    //listCan.add(can);
                                }
                            }
                        }
                        model.addAttribute("listCan", listCan);
                        Utils.drawHomePage(user.getUsername(), notifs, "generateAccount", "candidatureSupervisor", model);              
                    } else {
                        // Traitement administration
                        Utils.drawHomePage(user.getUsername(), notifs, "generateAccount", "conventionAdministration", model);
                    }
                    
                }
                //drawHomePage(tip,idUser,model);
                session.setAttribute("userID", userInfo.getID());
                session.setAttribute("userName", userInfo.getUSERNAME());
                session.setAttribute("userType", userInfo.getTYPE());
                
            }else{
                model.addAttribute("errormessage", " Wrong username or password");
                return "connection";
                
            }
        return "home";
             
    }      


}


